package service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.mysql.jdbc.Statement;

import service.User;
import common.Split;
import dbconnection.ConnectionFactory;

/**
 * Created by Administrator on 2016/12/15.
 */
public class UserImpl implements User{

    public int regSub(String str) throws Exception {  //chenzh,123456
        Split split=new Split();
        ArrayList<String> arrayList=split.splitList(str);

        ConnectionFactory connectionFactory=new ConnectionFactory();
        Connection connection=connectionFactory.getConnection();
        String sql="select userId from jc_user where userName=?";
        PreparedStatement preparedStatement;
        preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
        preparedStatement.setString(1,arrayList.get(0));
        ResultSet resultSet=preparedStatement.executeQuery();
        int userId = 0;
        while(resultSet.next()){
            userId=resultSet.getInt("userId");
        }
        int insertCom=0;
        if(userId==0){
            String insertSql="insert into jc_user (userName,pwd,logTimes) values (?,?,?)";
            preparedStatement=(PreparedStatement)connection.prepareStatement(insertSql);
            preparedStatement.setString(1,arrayList.get(0));
            preparedStatement.setString(2,arrayList.get(1));
            preparedStatement.setInt(3,0);
            insertCom=preparedStatement.executeUpdate();
            preparedStatement.close();
            if(insertCom==1){
            	initAll(arrayList.get(0));
                return 1;
            }else{
                System.out.println("fail");
            }
            connection.close();
        }else{
            return 0;
        }
        return 0;
    }
    
    public void initAll(String userName) throws Exception{
    	ConnectionFactory connectionFactory=new ConnectionFactory();
    	Connection connection=connectionFactory.getConnection();
    	String sql="select userId from jc_user where userName=?";
    	PreparedStatement preparedStatement;
    	preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
    	preparedStatement.setString(1, userName);
    	ResultSet resultSet=preparedStatement.executeQuery();
    	int userId = 0;
    	while(resultSet.next()){
    		userId=resultSet.getInt("userId");
    	}
    	sql="select price from jc_product";
    	preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
    	resultSet=preparedStatement.executeQuery();
    	String proPrice="";
    	while(resultSet.next()){
    		proPrice+=resultSet.getString("price")+",";
    	}
    	proPrice=proPrice.substring(0, proPrice.length()-1);
    	sql="select price from jc_house";
    	preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
    	resultSet=preparedStatement.executeQuery();
    	String housePrice="";
    	while(resultSet.next()){
    		housePrice+=resultSet.getString("price")+",";
    	}
    	housePrice=housePrice.substring(0, housePrice.length()-1);
    	sql="insert into jc_userproperty (userId,binderRatio,confidence,luck,health,coordinateX,coordinateY,day,money,productPrice,housePrice,deposit,houseProperty) "
    			+ "values (?,'100','100','100','100','23','23','1','3000',?,?,'3','1,0,0,0,0,0,0')";
    	preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
    	preparedStatement.setInt(1, userId);
    	preparedStatement.setString(2, proPrice);
    	preparedStatement.setString(3, housePrice);
    	int in;
    	in=preparedStatement.executeUpdate();
    	for(int i=0;i<5;i++){
    		in=0;
    		sql="insert into jc_userthings (userId,productId,number,price) values(?,?,'0','0')";
    		preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
        	preparedStatement.setInt(1, userId);
        	preparedStatement.setInt(2, i+1);
        	in=preparedStatement.executeUpdate();
    	}
    }

    public String loginSub(String str) throws Exception {  //chenzh,123456
        Split split=new Split();
        ArrayList<String> arrayList=split.splitList(str);
        ConnectionFactory connectionFactory=new ConnectionFactory();
        Connection connection=connectionFactory.getConnection();
        String sql="select userId,pwd,logTimes from jc_user where userName= ?";
        PreparedStatement preparedStatement;
        preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
        preparedStatement.setString(1,arrayList.get(0));
        ResultSet resultSet=preparedStatement.executeQuery();
        String pwd="";
        int logTimes=0;
        int userId=0;
        while(resultSet.next()){
            userId=resultSet.getInt("userId");
            pwd=resultSet.getString("pwd");
            logTimes=resultSet.getInt("logTimes");
        }
        int updateLog=0;
        sql="select logTimes from jc_user where userName=?";
        preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
        preparedStatement.setString(1, arrayList.get(0));
        resultSet=preparedStatement.executeQuery();
        while(resultSet.next()){
         updateLog=resultSet.getInt("logTimes");
        }
        updateLog+=1;
        sql="update jc_user set logTimes=? where userName=?";
        preparedStatement=(PreparedStatement)connection.prepareStatement(sql);
        preparedStatement.setInt(1, updateLog);
        preparedStatement.setString(2, arrayList.get(0));
        int update=0;
        update=preparedStatement.executeUpdate();
        
        
        connection.close();
        if(arrayList.get(1).equals(pwd))
            return 1+","+userId;
//        else if(arrayList.get(1).equals(pwd)&&logTimes==0)
//            return 2;
        else
            return 0+","+0;
    }

    @Override
	/**
	 * �����û���Ϣ�������ɹ��򷵻�1�����治�ɹ��򷵻�0
	 */
	public boolean save(String userMessage) {
		//��������ַ����и������
		Split split = new Split();
		ArrayList<String> saveMessage = split.splitSaveMessage(userMessage);
		//���³ɹ����ı�־
		boolean flag = true;
		/**
		 * 切割后下标对应的数据
		 * userID(0)，颜值(1)，自信(2)，运气(3)，生命(4)，当前坐标x(5)，当前坐标y(6)
		 * 天数(7)，金钱(8)，银行汇率(11)，拥有房产(12)
		 * 人物物品1名字（13），人物物品1数量（14），人物物品1价格（15），人物物品2名字（16），人物物品2数量（17），人物物品2价格（18）
		 * 人物物品3名字（19），人物物品3数量（20），人物物品3价格（21），人物物品4名字（22），人物物品4数量（23），人物物品4价格（24）
		 * 人物物品5名字（25），人物物品5数量（26），人物物品5价格（27），爱玛仕包价格(28)，阿玛尼牛仔双肩包价格(29)，阿迪达斯椰子价格(30)
		 * ，潘多拉戒指价格(31)，草雉剑价格(32)，手工品价格(33)，衣帽服饰价格(34)，电子配件价格(35)，化妆品价格(36)
		 * 烟酒价格(37)，智能手机价格(38)，PU皮包价格(39)，自行车价格(40)，盐价格(41)，死库水价格(42)
		 * 生蚝价格(43)，鳗鱼价格(44)，贝壳价格(45)，出租屋价格（46），北师大青年公寓价格(47)，二手京师家园小三房价格(48)
		 * 格力香樟价格(49)，龙光海悦云天复式价格(50)，情侣路边无敌海景大房价格(51)，野狸岛边小岛独栋别墅价格(52)
		 */
		try {
			ConnectionFactory connectionFactory = new ConnectionFactory();
			Connection connection = connectionFactory.getConnection(); 
			String sql = "select id from jc_userproperty where userId = ?" ;
			PreparedStatement prepardStatement = connection.prepareStatement(sql);
			prepardStatement.setString(1,saveMessage.get(0));
			
			ResultSet resultSet = prepardStatement.executeQuery();
			String s = "";
			for(int i = 0;i < 9;i++){
				s += saveMessage.get(i);
				s += ",";
			}
			s = s + "'" + saveMessage.get(10) + "',";
			String str = "";
			for(int i = 26 ;i < 44;i++){
				str += saveMessage.get(i);
				str += ",";
			}
			String house = "";
			for(int i = 44;i < saveMessage.size();i++){
				house += saveMessage.get(i);
				house+= ",";
			}
			house = house.substring(0, house.length() - 1);
//			System.out.println(resultSet.next());
			String target = s + "'" +  house + "','" + str + "'"; 
			System.out.println("---"+target);
			Statement statement = (Statement) connection.createStatement();
			if(resultSet.next()){
				
				sql = "update jc_userproperty set binderRatio = " + saveMessage.get(1)
						+ " ,confidence = " + saveMessage.get(2) 
						+ " ,luck = " + saveMessage.get(3)
						+ " ,health = " + saveMessage.get(4)
						+ " ,coordinateX = " + saveMessage.get(5)
						+ " ,coordinateY = " + saveMessage.get(6)
						+ " ,day = " + saveMessage.get(7)
						+ " ,money = " + saveMessage.get(8)
						+ " ,houseProperty = '" + saveMessage.get(10)
						+ "',housePrice = '" + house
						+ "',productPrice = '" + str
						+ "'where userId = " +saveMessage.get(0);
				//System.out.println("-----------------------" + sql);
				if(statement.executeUpdate(sql) <= 0)
					flag = false;
			}
			else{
				System.out.println(target);
				sql = "insert into jc_userproperty (userId,binderRatio,luck,confidence,health,coordinateX"
						+ ",coordinateY,day,money,houseProperty,housePrice,productPrice) values"
						+ "(" + target +")";
				//System.out.println("+++++++++++++++" + sql);
				if(statement.execute(sql))
					flag = false;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return flag;
	}

	/**
	 * ������Ʒ��¼
	 */
	@Override
	public boolean bugThings(String str) {
		boolean flag = true;
		Split split = new Split();
		
		
		try {
			ConnectionFactory connectionFactory = new ConnectionFactory();
			Connection connection = connectionFactory.getConnection();
			
			ArrayList<String> arrayList = split.splitList(str);
			for(int i = 1;i < 52;i+=3){
				String sql = "insert into jc_tradingrecord (userId,productName,number,tradingMoney) values (?,?,?,?)";
				//���ѭ��Ϊʲôִֻ����һ�Σ���
				PreparedStatement preparedStatement = (PreparedStatement)connection.prepareStatement(sql);
				System.out.println("i = " + i);
				System.out.println(Integer.parseInt(arrayList.get(i+1)));
				if(Integer.parseInt(arrayList.get(i+1)) != 0){
					
					System.out.println("ִ�гɹ�"); 
					preparedStatement.setInt(1, Integer.parseInt(arrayList.get(0)));
					preparedStatement.setString(2, arrayList.get(i));
					preparedStatement.setInt(3, Integer.parseInt(arrayList.get(i + 1)));
					preparedStatement.setInt(4, Integer.parseInt(arrayList.get(i + 2)));
					
					preparedStatement.executeUpdate();
	
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO: handle exception
		}
		return flag;
	}
    
    public boolean getBag(String str) throws Exception{
		Split split = new Split();
		ArrayList<String> list = split.splitList(str);
		String sql = "select id from jc_userthings where userId = " + list.get(0);
		ConnectionFactory connectionFactory = new ConnectionFactory();
		Connection connection = connectionFactory.getConnection();
		PreparedStatement preparrdStatement2 = connection .prepareStatement(sql);
		ResultSet resultSet1 = preparrdStatement2.executeQuery();
		resultSet1.next();
		boolean flag = true;
		int id = resultSet1.getInt(1);
		sql = "update jc_userthings set productName=?,number=?,price=?,productId=? where id = ?";
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		int count = 0;
		for(int i = 1;i < list.size();i+=4){
			if(Integer.parseInt(list.get(i + 3)) != 0){
				preparedStatement.setString(1, list.get(i + 1));
				preparedStatement.setInt(2,Integer.parseInt(list.get(i + 2)));
				preparedStatement.setInt(3, Integer.parseInt(list.get(i + 3)));
				preparedStatement.setInt(4, Integer.parseInt(list.get(i)));
				preparedStatement.setInt(5, id+count);
				count ++;
				preparedStatement.executeUpdate();
			
			}
			System.out.println("count = "+count);
			if(count < 5){
				System.out.println("不足五个");
				for(int j = count ;j < 5;j++){
					preparedStatement.setString(1, "0");
					preparedStatement.setInt(2,0);
					preparedStatement.setInt(3,0);
					preparedStatement.setInt(4,0);
					preparedStatement.setInt(5,id+j);
					preparedStatement.executeUpdate();
				}
			}
		}
		return flag;
	}
    
}
